﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Emporium_Web.Controls;
using Emporium_Web.Enums;
using Emporium_Web.DBML;
using System.Linq.Expressions;



namespace Emporium_Web
{
    public partial class EstiloList : System.Web.UI.Page
    {
        public string SortExpression
        {
            get
            {
                return ViewState["gv_SortExpression"] == null ? "" : ViewState["gv_SortExpression"].ToString();
            }
            set
            {
                ViewState["gv_SortExpression"] = value;
            }
        }

        public string SortDirection
        {
            get
            {
                return ViewState["gv_SortDirection"] == null ? "" : ViewState["gv_SortDirection"].ToString();
            }
            set
            {
                ViewState["gv_SortDirection"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            warningMessage.Visible = false;
            errorMessage.Visible = false;
            try
            {
                if (!IsPostBack)
                {
                    Master.ActualizaMenu(MenuPrincipal.Desarrollo, (int)MenuDesarrollo.Estilo);
                    Master.AgregarBreadcrumb("Estilos", "#", true);
                    Master.AgregarBreadcrumb("Listado", "EstiloList.aspx", false);                   
                    ListarEstilos();
                }
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }       

        protected void btnBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                ListarEstilos();
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void btnAdicionar_Click(object sender, EventArgs e)
        {
            Response.Redirect("EstiloForm.aspx?Operacion=" + (int)AccionesForm.Adicionar);         
        }

        protected void btnModificar_Click(object sender, EventArgs e)
        {
            try
            {
                int codigo = 0;
                if (Int32.TryParse(hdnSeleccion.Value.ToString(), out codigo))
                {
                    Response.Redirect("EstiloForm.aspx?Operacion=" + (int)AccionesForm.Modificar + "&EstiloId=" + codigo);
                }
                else
                {
                    warningMessage.Visible = true;
                    lblWarningMessage.Text = Resources.MensajesValidacion.NoItemSelected;
                }
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void btnConsultar_Click(object sender, EventArgs e)
        {
            try
            {
                int codigo = 0;
                if (Int32.TryParse(((LinkButton)sender).Text, out codigo))
                {
                    Response.Redirect("EstiloForm.aspx?Operacion=" + (int)AccionesForm.Consultar + "&EstiloId=" + codigo);
                }
                else
                {
                    warningMessage.Visible = true;
                    lblWarningMessage.Text = Resources.MensajesValidacion.NoItemSelected;
                }
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void btnEliminar_Click(object sender, EventArgs e)
        {
            try
            {
                int codigo = 0;
                if (Int32.TryParse(hdnSeleccion.Value.ToString(), out codigo))
                {
                    Eliminar();
                    ListarEstilos();
                }
                else
                {
                    warningMessage.Visible = true;
                    lblWarningMessage.Text = Resources.MensajesValidacion.NoItemSelected;
                }
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void btnImagenes_Click(object sender, EventArgs e)
        {
            try
            {
                int codigo = 0;
                if (Int32.TryParse(hdnSeleccion.Value.ToString(), out codigo))
                {
                    Response.Redirect("EstiloImagenes.aspx?EstiloId=" + codigo);
                }
                else
                {
                    warningMessage.Visible = true;
                    lblWarningMessage.Text = Resources.MensajesValidacion.NoItemSelected;
                }
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }


        protected void btnVariantes_Click(object sender, EventArgs e)
        {
            try
            {
                int codigo = 0;
                if (Int32.TryParse(hdnSeleccion.Value.ToString(), out codigo))
                {
                    Response.Redirect("VariantesXEstilo.aspx?EstiloId=" + codigo);
                }
                else
                {
                    warningMessage.Visible = true;
                    lblWarningMessage.Text = Resources.MensajesValidacion.NoItemSelected;
                }
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void btnConsumos_Click(object sender, EventArgs e)
        {
            try
            {
                int codigo = 0;
                if (Int32.TryParse(hdnSeleccion.Value.ToString(), out codigo))
                {
                    Response.Redirect("ConsumosXEstilo.aspx?EstiloId=" + codigo);
                }
                else
                {
                    warningMessage.Visible = true;
                    lblWarningMessage.Text = Resources.MensajesValidacion.NoItemSelected;
                }
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }    

        protected void gvPagerPageChanged(object sender, DataNavigatorEventArgs e)
        {
            try
            {
                ListarEstilos();
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void gvEstilos_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                if (this.SortExpression != null && this.SortExpression.Equals(e.SortExpression))
                {
                    this.SortDirection = this.SortDirection.ToUpper().Equals("ASC") ? "DES" : "ASC";
                }
                else
                {
                    this.SortDirection = e.SortDirection.ToString().Substring(0, 3);
                }

                this.SortExpression = e.SortExpression;

                ListarEstilos();
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void gvEstilos_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {

                if (gvEstilos.HeaderRow == null)
                {
                    return;
                }

                this.SortExpression = e.CommandArgument != null ? e.CommandArgument.ToString() : "Id";
                this.SortDirection = e.CommandName.Equals("SortUp") ? "ASC" : "DES";
                ListarEstilos();

                if (e.CommandName.Equals("Imagenes"))
                {
                    TablasDataContext database = new TablasDataContext();
                    var imagenesVisibles = (from imagenes in database.DE_EstiloImagen
                                            where imagenes.EstiloId == Convert.ToInt32(e.CommandArgument.ToString())
                                               && imagenes.Visible == 'Y' 
                                             select imagenes);

                    var imagenesDefault = (from imagenes in database.DE_EstiloImagen
                                            where imagenes.EstiloId == Convert.ToInt32(e.CommandArgument.ToString())
                                               && imagenes.Defecto == 'Y'
                                           select imagenes).FirstOrDefault();

                    List<Imagen> lstImagenes = new List<Imagen>();

                    foreach (var item in imagenesVisibles)
                    {
                        lstImagenes.Add(new Imagen()
                        {
                            Defecto = item.Defecto.Value,
                            Descripcion = item.Descripcion,
                            EstiloId = item.EstiloId,
                            FechaRegistro = item.FechaRegistro.Value,
                            Id = item.Id,
                            Visible = item.Visible.Value,
                            Ruta = item.Ruta
                        });
                    }

                    if (imagenesDefault != null)
                    {
                        estiloImagenShow.ImagenesTemp = lstImagenes;
                        estiloImagenShow.CodigoEstilo = Convert.ToInt32(e.CommandArgument.ToString());
                        estiloImagenShow.CodigoImagen = imagenesDefault.Id;
                        estiloImagenShow.Show();
                    }
                }      

            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        private void ActivaIconoOrdenamiento()
        {
            if (gvEstilos.HeaderRow == null)
            {
                return;
            }

            LinkButton lnkSender = null;
            LinkButton lnkSortDown = null;
            LinkButton lnkSortUp = null;

            if (this.SortDirection != null && this.SortDirection.ToUpper().Equals("ASC"))
            {
                lnkSender = (LinkButton)gvEstilos.HeaderRow.FindControl("lnkSortUp" + this.SortExpression);
                if (lnkSender != null)
                    lnkSortDown = (LinkButton)gvEstilos.HeaderRow.FindControl(lnkSender.ID.Replace("SortUp", "SortDown"));
                if (lnkSortUp != null) lnkSortDown.CssClass = "sort-down";
                if (lnkSender != null) lnkSender.CssClass = "sort-up active";
            }
            else
            {
                lnkSender = (LinkButton)gvEstilos.HeaderRow.FindControl("lnkSortDown" + this.SortExpression);
                if (lnkSender != null)
                    lnkSortUp = (LinkButton)gvEstilos.HeaderRow.FindControl(lnkSender.ID.Replace("SortDown", "SortUp"));

                if (lnkSortUp != null) lnkSortUp.CssClass = "sort-up";
                if (lnkSender != null) lnkSender.CssClass = "sort-down active";
            }
        }

        private void ListarEstilos()
        {
            TablasDataContext database = new TablasDataContext();
       
            int idEstilo = string.IsNullOrEmpty(txtCodigo.Text) ? 0 : Convert.ToInt32(txtCodigo.Text);
             
            var listarQuery = (from estilos in database.DE_Estilo
                               where (estilos.Id == idEstilo || idEstilo == 0)
                                  && (estilos.TG_Cliente.Nombre.Contains(clienteSearch.NombreSeleccionado) || clienteSearch.NombreSeleccionado == string.Empty)
                                  && (estilos.TG_Temporada.Descripcion.Contains(temporadaSearch.DescripcionSeleccionado) || temporadaSearch.DescripcionSeleccionado == string.Empty)                                                                
                               select estilos);

            listarQuery = OrdenarQuery(listarQuery);

            var listarQuery1 = listarQuery.Skip((gvPager.CurrentPage - 1) * gvPager.PageSize).Take(gvPager.PageSize).ToList();

            gvEstilos.DataSource = listarQuery1;            
            gvEstilos.DataBind();

            int totalReg = listarQuery.Count();

            if (totalReg > 0)
            {
                gvEstilos.UseAccessibleHeader = false;
                gvEstilos.HeaderRow.TableSection = TableRowSection.TableHeader;
                gvPager.Visible = true;
                gvPager.TotalRowCount = totalReg;
                warningMessage.Visible = false;
            }
            else
            {
                lblWarningMessage.Text = Resources.MensajesValidacion.NoDataFound;
                warningMessage.Visible = true;
                gvPager.Visible = false;
            }

            lblMensajeGridFooter.Text = String.Format(Resources.MensajesValidacion.GridFooterMessage, totalReg);
            ActivaIconoOrdenamiento();
        }

        private IQueryable<DE_Estilo> OrdenarQuery(IQueryable<DE_Estilo> listarQuery)
        {
            if (this.SortExpression == null || this.SortExpression.Trim().Equals(""))
            {
                this.SortExpression = "Id";
            }

            if (this.SortDirection == null || this.SortDirection.Trim().Equals(""))
            {
                this.SortDirection = "DES";
            }

            if (this.SortExpression == "Id")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Id);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Id);
                }
            }
            else if (this.SortExpression == "Descripcion")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Descripcion);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Descripcion);
                }
            }
            else if (this.SortExpression == "Cliente")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.TG_Cliente.Nombre);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.TG_Cliente.Nombre);
                }
            }
            else if (this.SortExpression == "Temporada")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.TG_Temporada.Descripcion);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.TG_Temporada.Descripcion);
                }
            }
            else if (this.SortExpression == "CodigoCliente")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.CodigoCliente);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.CodigoCliente);
                }
            }
            else if (this.SortExpression == "FechaRegistro")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.FechaRegistro);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.FechaRegistro);
                }
            }

            return listarQuery;
        }

        private void Eliminar()
        {
            int id = 0;
            if (Int32.TryParse(hdnSeleccion.Value.ToString(), out id))
            {
                TablasDataContext database = new TablasDataContext();

                var listVariantes = (from variantes in database.DE_Variante
                                     where variantes.Estilo_Id == id
                                     select variantes);
                foreach (var itemVar in listVariantes)
                {
                    var colores = (from combinacionColor in database.DE_VarianteItemCombinacionColor
                                   where combinacionColor.Variante_Id == itemVar.Variante_Id
                                   select combinacionColor);
                    foreach (var item in colores)
                    {
                        database.DE_VarianteItemCombinacionColor.DeleteOnSubmit(item);
                    }

                    var items = (from varianteItems in database.DE_VarianteItem
                                 where varianteItems.Variante_Id == itemVar.Variante_Id
                                 select varianteItems);
                    foreach (var item in items)
                    {
                        database.DE_VarianteItem.DeleteOnSubmit(item);
                    }

                    var componentes = (from varianteComponente in database.DE_VarianteComponente
                                       where varianteComponente.Variante_Id == itemVar.Variante_Id
                                       select varianteComponente);
                    foreach (var item in componentes)
                    {
                        database.DE_VarianteComponente.DeleteOnSubmit(item);
                    }

                    database.DE_Variante.DeleteOnSubmit(itemVar);
                }

                var listCombinaciones = (from combinaciones in database.DE_EstiloCombinacion
                                     where combinaciones.Estilo_Id == id
                                    select combinaciones);
                foreach (var item in listCombinaciones)
                {
                    database.DE_EstiloCombinacion.DeleteOnSubmit(item);
                }

                var listImagenes = (from imagenes in database.DE_EstiloImagen
                                     where imagenes.EstiloId == id
                                     select imagenes);
                foreach (var item in listImagenes)
                {
                    database.DE_EstiloImagen.DeleteOnSubmit(item);
                }

                var listTallas = (from tallas in database.DE_EstiloTalla
                                    where tallas.Estilo_Id == id
                                    select tallas);
                foreach (var item in listTallas)
                {
                    database.DE_EstiloTalla.DeleteOnSubmit(item);
                }

                var estilo = (from estilos in database.DE_Estilo
                               where estilos.Id == id
                               select estilos).First();

                if (estilo != null)
                {
                    database.DE_Estilo.DeleteOnSubmit(estilo);

                    database.SubmitChanges();
                }

                hdnSeleccion.Value = "";
            }
            else
            {
                warningMessage.Visible = true;
                lblWarningMessage.Text = Resources.MensajesValidacion.NoItemSelected;
            }
        }         
    }
}